package com.citi.infocambio.siscomex.client.http;


import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;




public class HttpClientFactory {
	
	private static X509HostnameVerifier hv = new DummyX509HostnameVerifier();
	private static X509TrustManager tm = new DummyX509TrustManager();
	
	public static HttpClient getHttpClient() throws Exception { 
		HttpClient client = new DefaultHttpClient();
		wrapHttpClient(client);
		return client;
	}
	
	
	private static class DummyX509HostnameVerifier implements X509HostnameVerifier {

		public boolean verify(String arg0, SSLSession arg1) {
			return true;
		}

		public void verify(String host, SSLSocket ssl) throws IOException {
		}

		public void verify(String host, X509Certificate cert) throws SSLException {
		}

		public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
		} 
		
	}
	
	private static class DummyX509TrustManager implements X509TrustManager {

		public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[0];
		} 
		
	}


	private static void wrapHttpsUrlConnection(SSLContext context) {
		HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
		HttpsURLConnection.setDefaultHostnameVerifier(hv);
	}

	private static void wrapHttpClient(HttpClient httpClient) throws Exception {
		SSLContext ctx = SSLContext.getInstance("TLS");
		TrustManager[] trustmanagers;		
		trustmanagers = new TrustManager[] { tm };
		
		ctx.init(null, trustmanagers, null);
		wrapHttpsUrlConnection(ctx);
		SSLSocketFactory ssf = new SSLSocketFactory(ctx);
		ssf.setHostnameVerifier(hv);

		ClientConnectionManager ccm = httpClient.getConnectionManager();
		SchemeRegistry sr = ccm.getSchemeRegistry();
		sr.register(new Scheme("https", ssf, 443));
	}


}
